package cn.lovelysia.ymcc.service.impl;

import cn.lovelysia.ymcc.domain.MessageSms;
import cn.lovelysia.ymcc.dto.SendSmsParamDto;
import cn.lovelysia.ymcc.exception.BusinessException;
import cn.lovelysia.ymcc.feignclient.IUserFeignClient;
import cn.lovelysia.ymcc.result.JSONResult;
import cn.lovelysia.ymcc.service.IMessageSmsService;
import cn.lovelysia.ymcc.service.IVerifyCodeService;
import cn.lovelysia.ymcc.util.StrUtils;
import cn.lovelysia.ymcc.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private IUserFeignClient userFeignClient;

    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public String getImageCode(String key) {
        //通过StrUtils生成4位的图形验证码code --字符串
        String code = StrUtils.getComplexRandomString(4);
        //将key和图形验证码code保存到Redis，5分钟后过期
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
        //将图形验证码写到图片中并且使用base64编码
        String base64Str = VerifyCodeUtils.verifyCode(115,40,code);
        return base64Str;
    }

    @Override
    public void getSmsCode(SendSmsParamDto sendSmsParamDto) {
        String phone = sendSmsParamDto.getMobile();
        String imageCode = sendSmsParamDto.getImageCode();
        String imageCodeKey = sendSmsParamDto.getImageCodeKey();
        //1.空值校验
//        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(imageCode)){
//            throw new BusinessException("信息不能为空");
//        }
        //2.校验 - 图形验证码是否过期
        Object obj = redisTemplate.opsForValue().get(imageCodeKey);
        if(obj==null){
            throw new BusinessException("图形验证码过期");
        }
        if(!imageCode.equalsIgnoreCase(obj.toString())){
            throw new BusinessException("图形验证码错误");
        }

        //3.校验 - 手机验证码是否注册过
        JSONResult result = userFeignClient.findByPhone(phone);
        if(result.getData() != null){
            throw new BusinessException("该手机已经注册");
        }

        Object blacklistObj = redisTemplate.opsForValue().get("blacklist:"+phone);
        if(blacklistObj!=null){//黑名单有数据
            throw new BusinessException("检测到你的操作异常，请联系相关工作人员");
        }
        Object countObj = redisTemplate.opsForValue().get("count:" + phone);
        if(countObj==null){
            redisTemplate.opsForValue().set("count:" + phone,0,10,TimeUnit.MINUTES);
        }
        redisTemplate.opsForValue().increment("count:" + phone);//count自增
        Long count = Long.valueOf(redisTemplate.opsForValue().get("count:" + phone).toString());
        if(count>9){
            //加入黑名单
            redisTemplate.opsForValue().set("blacklist:"+phone,phone,30,TimeUnit.MINUTES);
        }

        //4.获取手机验证码【register:电话 - 9527（验证码）:时间戳】
        Object phoneCodeObj = redisTemplate.opsForValue().get("register:" + phone);
        String code = null;
        if(phoneCodeObj == null){//第一次发送验证码，或者验证码已过期
            code = StrUtils.getRandomString(6);
        }else {
            //上一次获取验证码的时间戳
            long oldTime = Long.parseLong(phoneCodeObj.toString().split(":")[1]);
            //当前时间戳
            long newTime = System.currentTimeMillis();
            if((newTime-oldTime)<1*60*1000){//一分钟内重复请求获取验证码
                throw new BusinessException("请勿重复获取验证码");
            }
            code = phoneCodeObj.toString().split(":")[0];
        }
        //5.将验证码保存到Redis，3分钟有效
        redisTemplate.opsForValue().set("register:"+phone,code+":"+System.currentTimeMillis(),3, TimeUnit.MINUTES);
        //6.向手机发送验证码
        //SmsUtils.sendSms(phone,"验证码:"+code+",请在3分钟内使用！");
        System.out.println("验证码:" + code + ",请在3分钟内使用！");
        //7.存储短信发送记录
        MessageSms messageSms = new MessageSms();
        messageSms.setTitle("手机验证码注册");
        messageSms.setContent("验证码为:" + code + ",请在3分钟内使用！");
        messageSms.setSendTime(new Date());
        messageSms.setPhone(phone);
        ServletRequestAttributes  requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        String addr = requestAttributes.getRequest().getRemoteAddr();//获取IP地址
        messageSms.setIp(addr);
        messageSmsService.insert(messageSms);
    }
}
